package com.biboheart.brick.adapter.converts;

import com.biboheart.brick.adapter.Converter;
import com.biboheart.brick.adapter.TypeConverter;
import com.biboheart.brick.utils.CheckUtils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 填充转换器
 * 例如：
 * 输入为{"name": "张三", "age": 18}，辅助参数为"{[name]}今年{[age]}岁"，转换为"张三今年18岁"
 */
public class FillConverter implements Converter {
    @SuppressWarnings("unchecked")
    @Override
    public <T> T convert(Object input, String auxiliary, Class<T> valueType) {
        if (null == input || null == auxiliary) {
            return null;
        }
        if (auxiliary.isEmpty()) {
            return TypeConverter.convert(auxiliary, valueType);
        }
        Set<String> transitions = new HashSet<>();
        Pattern pattern = Pattern.compile("(?=\\{\\[)(.+?)(]})");
        Matcher matcher = pattern.matcher(auxiliary);
        while (matcher.find()) {
            transitions.add(matcher.group());
        }
        if (CheckUtils.isEmpty(transitions)) {
            return TypeConverter.convert(auxiliary, valueType);
        }
        Map<String, Object> refMap = TypeConverter.convert(input, Map.class);
        for (String transition : transitions) {
            String[] transitionArr = transition.replace("{[", "").replace("]}", "").split("\\|");
            String key = transitionArr[0].trim();
            Object val = refMap.get(key);
            if (null == val) {
                auxiliary = auxiliary.replace(transition, "");
            } else {
                auxiliary = auxiliary.replace(transition, TypeConverter.convert(val, String.class));
            }
        }
        return TypeConverter.convert(auxiliary, valueType);
    }
}
